<template>
  <form @submit.prevent="handleRegister" class="space-y-4">
    <div>
      <label class="block text-sm font-medium text-gray-700 mb-1">
        用户名
      </label>
      <input v-model="registerForm.username" type="text" maxlength="8" :class="[
        'w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-bsr focus:border-transparent outline-none transition-all',
        fieldErrors.username ? 'border-red-500' : 'border-gray-300'
      ]" placeholder="请输入用户名（最多8位）" @input="clearFieldError('username')" />
      <p v-if="fieldErrors.username" class="mt-1 text-sm text-red-600">
        {{ fieldErrors.username }}
      </p>
    </div>
    <div>
      <label class="block text-sm font-medium text-gray-700 mb-1">
        密码
      </label>
      <input v-model="registerForm.password" type="password" maxlength="16" :class="[
        'w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-bsr focus:border-transparent outline-none transition-all',
        fieldErrors.password ? 'border-red-500' : 'border-gray-300'
      ]" placeholder="请输入密码" @input="() => {
          clearFieldError('password')
          clearFieldError('confirmPassword')
        }" />
      <p v-if="fieldErrors.password" class="mt-1 text-sm text-red-600">
        {{ fieldErrors.password }}
      </p>
    </div>

    <div>
      <label class="block text-sm font-medium text-gray-700 mb-1">
        确认密码
      </label>
      <input v-model="registerForm.confirmPassword" type="password" maxlength="16" :class="[
        'w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-bsr focus:border-transparent outline-none transition-all',
        fieldErrors.confirmPassword ? 'border-red-500' : 'border-gray-300'
      ]" placeholder="请再次输入密码" @input="clearFieldError('confirmPassword')" />
      <p v-if="fieldErrors.confirmPassword" class="mt-1 text-sm text-red-600">
        {{ fieldErrors.confirmPassword }}
      </p>
    </div>

    <div>
      <label class="block text-sm font-medium text-gray-700 mb-1">验证码</label>

      <!-- 验证码图片显示区域 -->
      <div v-if="captchaImage" class="mb-3">
        <div class="flex items-center space-x-3">
          <div class="w-full">
            <img :src="captchaImage" alt="验证码" class="h-15 object-contain border border-gray-300 rounded-lg bg-gray-50"
              @click="$emit('refresh-captcha')" />
          </div>
          <!-- <button
            type="button"
            @click="$emit('refresh-captcha')"
            :disabled="sendingCode"
            class="px-3 py-1 text-sm bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-colors disabled:opacity-50"
            title="刷新验证码"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
            </svg>
          </button> -->
        </div>
        <p class="mt-1 text-xs text-gray-500">点击图片可刷新验证码</p>
      </div>

      <!-- 验证码输入框 -->
      <div class="flex items-center">
        <div v-if="captchaImage" class="flex-1">
          <input v-model="registerForm.code" type="text" maxlength="4" :class="[
            'w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-bsr focus:border-transparent outline-none transition-all',
            fieldErrors.code ? 'border-red-500' : 'border-gray-300'
          ]" placeholder="输入验证码" @input="handleCodeInput($event)" />
          <p v-if="fieldErrors.code" class="mt-1 text-sm text-red-600">
            {{ fieldErrors.code }}
          </p>
        </div>
        <button v-if="!captchaImage" type="button" @click="$emit('send-code', registerForm.username)"
          :disabled="!registerForm.username || !registerForm.password"
          class="flex-1 px-3 py-2 bg-bsr text-white rounded-lg disabled:opacity-50">
          <span>点击获取验证码</span>
        </button>
      </div>
    </div>

    <div v-if="errorMessage" class="text-red-600 text-sm text-center bg-red-50 p-2 rounded">
      {{ errorMessage }}
    </div>

    <button type="submit" :disabled="loading"
      class="w-full bg-bsr text-white py-3 rounded-lg font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
      <span v-if="!loading">注册</span>
      <span v-else class="flex items-center justify-center">
        <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none"
          viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor"
            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
          </path>
        </svg>
        注册中...
      </span>
    </button>
  </form>
</template>

<script setup lang="ts">
interface Props {
  loading?: boolean
  errorMessage?: string
  sendCountdown?: number
  captchaImage?: string
}

interface Emits {
  (e: 'send-code', username: string): void
  (e: 'refresh-captcha'): void
  (e: 'register', data: { username: string; password: string; code: string }): void
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  errorMessage: '',
  captchaImage: ''
})

const emit = defineEmits<Emits>()

// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  code: ''
})

// 字段验证错误
const fieldErrors = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  code: ''
})
// 验证函数
const validateField = (fieldName: 'username' | 'password' | 'confirmPassword' | 'code', value: string) => {
  // 检查是否为空
  if (!value || value.trim() === '') {
    const fieldNameMap: Record<string, string> = {
      username: '用户名',
      password: '密码',
      confirmPassword: '确认密码',
      code: '验证码'
    }
    fieldErrors[fieldName] = `请填写${fieldNameMap[fieldName]}`
    return false
  }

  // 检查长度限制
  switch (fieldName) {
    case 'username':
      if (value.length > 8) {
        fieldErrors[fieldName] = '用户名长度不能超过8位'
        return false
      }
      // 检查用户名格式：仅能使用数字、字母、"_"及"-"
      if (!/^[a-zA-Z0-9_-]+$/.test(value)) {
        fieldErrors[fieldName] = '用户名仅能使用数字、字母、"_"及"-"'
        return false
      }
      // 检查不能为纯数字
      if (/^\d+$/.test(value)) {
        fieldErrors[fieldName] = '用户名不能为纯数字'
        return false
      }
      break
    case 'password':
      if (value.length < 8) {
        fieldErrors[fieldName] = '密码长度必须至少8位'
        return false
      }
      if (value.length > 16) {
        fieldErrors[fieldName] = '密码长度不能超过16位'
        return false
      }

      // 检查密码复杂度：必须包含字母、数字、特殊符号中的至少两种
      const hasLetter = /[a-zA-Z]/.test(value)
      const hasNumber = /[0-9]/.test(value)
      const hasSpecial = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value)

      const categoryCount = [hasLetter, hasNumber, hasSpecial].filter(Boolean).length

      if (categoryCount < 2) {
        fieldErrors[fieldName] = '密码必须包含字母、数字、特殊符号中的至少两种'
        return false
      }
      break
    case 'confirmPassword':
      if (value.length < 8) {
        fieldErrors[fieldName] = '确认密码长度必须至少8位'
        return false
      }
      if (value.length > 16) {
        fieldErrors[fieldName] = '确认密码长度不能超过16位'
        return false
      }
      // 检查两次密码是否一致
      if (registerForm.password && value !== registerForm.password) {
        fieldErrors[fieldName] = '两次输入的密码不一致'
        return false
      }
      break
    case 'code':
      if (value.length !== 4) {
        fieldErrors[fieldName] = '验证码长度必须是4位'
        return false
      }
      break
  }

  fieldErrors[fieldName] = ''
  return true
}

// 实时清除错误
const clearFieldError = (fieldName: 'username' | 'password' | 'confirmPassword' | 'code') => {
  fieldErrors[fieldName] = ''
}

// 处理验证码输入，只允许字母和数字
const handleCodeInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  const value = target.value

  // 只保留字母和数字
  const alphanumericValue = value.replace(/[^a-zA-Z0-9]/g, '')

  // 更新表单值
  registerForm.code = alphanumericValue

  // 清除错误
  clearFieldError('code')
}

const validateRegisterForm = () => {
  let isValid = true
  isValid = validateField('username', registerForm.username) && isValid
  isValid = validateField('password', registerForm.password) && isValid
  isValid = validateField('confirmPassword', registerForm.confirmPassword) && isValid
  isValid = validateField('code', registerForm.code) && isValid
  return isValid
}

// 处理注册
const handleRegister = async () => {
  // 验证表单
  if (!validateRegisterForm()) {
    return
  }

  emit('register', {
    username: registerForm.username,
    password: registerForm.password,
    code: registerForm.code
  })
}

// 暴露方法给父组件
defineExpose({
  resetForm: () => {
    registerForm.username = ''
    registerForm.password = ''
    registerForm.confirmPassword = ''
    registerForm.code = ''
    fieldErrors.username = ''
    fieldErrors.password = ''
    fieldErrors.confirmPassword = ''
    fieldErrors.code = ''
  },
  registerForm // 暴露表单数据给父组件
})
</script>

<style scoped>
/* 输入框焦点效果 */
input:focus {
  box-shadow: 0 0 0 3px rgba(194, 48, 28, 0.1);
}

/* 按钮悬停效果 */
button {
  transition: all 0.2s ease;
}
</style>
